package com.twoscreen;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CronServlet extends HttpServlet  {
	private static PersistenceManager pm = PMF.get().getPersistenceManager();
	private static final Logger log = Logger.getLogger("com.twoscreen.CronDailyServlet.java");
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		log.info("Cron job request received (GET)");
		clearExpiredPlayScreenIDs();
	}
	
	protected static void clearExpiredPlayScreenIDs() {
		log.info("Cron job started");
		Query q = pm.newQuery(PlayerScreen.class);
		Long now = new Date().getTime();
		q.setFilter(PlayerScreen.getPsValidUntilPropertyName() + " < " + now);
		
		try {
			@SuppressWarnings("unchecked")
			List<PlayerScreen> results = (List<PlayerScreen>) q.execute();
			for (PlayerScreen result : results) {
				log.info("Key expired. ID: " + result.getKey().getId() + 
						", expired: " + new Date(result.getValidUntil()) +
						", now date: " + new Date(now));
				pm.deletePersistent(result);
			}
		} finally {
			q.closeAll();
		}
		log.info("Cron job end");
	}
	
}
